// 2025/3/7
// https://leetcode.cn/problems/add-two-numbers/?envType=study-plan-v2&envId=top-100-liked
// 两数相加

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode head;
            ListNode *cur = &head;
            int out = 0, ret = 0;
            while(l1 != nullptr || l2 != nullptr)
            {
                ret = out;
                if(l1 != nullptr)
                {
                    ret += l1->val;
                    l1 = l1->next;
                }
                if(l2 != nullptr)
                {
                    ret += l2->val;
                    l2 = l2->next;
                }
                out = ret / 10;
                cur->next = new ListNode(ret % 10);
                cur = cur->next;
            }
            if(out != 0) cur->next = new ListNode(out);
            
            return head.next;
        }
    };